<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import PatrolInfoApi from '@/api/linePatrol'
import type { PatrolInspectionType } from '@/api/linePatrol/type'
import { ElMessage } from 'element-plus'
import Detail from './components/Detail.vue'
import * as XLSX from 'xlsx'
import { useDeptStore } from '@/store/modules/dept'
import { useEquipStore } from '@/store/modules/equip'
const DeptStore = useDeptStore()
const EquipStore = useEquipStore()
if (DeptStore.DeptListTypeDetail.length == 0 || DeptStore.DeptListTypeDetail.length == undefined) {
  DeptStore.setFacilityTypeDetail()
}
if (
  EquipStore.getFacilityTypeTree.length == 0 ||
  EquipStore.getFacilityTypeTree.length == undefined
) {
  EquipStore.setFacilityTypeTree()
}
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const i = await PatrolInfoApi.PatrolInspection({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await PatrolInfoApi.DeletpatrolInfo(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },

  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'facName',
    label: t('巡检点名称'),
    search: {
      componentProps: {
        placeholder: '巡检点名称'
      }
    }
  },
  {
    field: 'qrCode',
    label: t('二维码'),
    search: {
      hidden: true
    }
  },
  {
    field: 'faciName',
    label: t('类型'),
    // formatter: (_: Recordable, __: any, cellValue: string) => {
    //   return flatData(EquipStore.FacilityTypeTree).map((item) => {
    //     if (item.id == cellValue) {
    //       return t(item.label);
    //     }
    //   });
    // },
    // detail: {
    //   slots: {
    //     default: (data: any) => {
    //       return (<span>{DeptStore.getDeptName(data.coId)[0].deptName}</span>)
    //     },
    //   },
    // },
    search: {
      hidden: true
    }
  },

  {
    field: 'coId',
    width: 150,
    label: t('子公司'),
    formatter: (_: Recordable, __: any, cellValue: number) => {
      if (cellValue !== undefined && cellValue) {
        return DeptStore.getDeptName(cellValue)[0].deptName
      }
    },
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <span>{DeptStore.getDeptName(data.coId)[0]?.deptName}</span>
        }
      }
    }
  },
  {
    field: 'userAreaId',
    width: 100,
    label: t('用户片区'),
    search: {
      componentProps: {
        placeholder: '用户片区'
      }
    }
  },
  {
    field: 'factoryStation',
    label: t('厂站'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'surveyLocUuid',
    width: 150,
    label: t('关联地图'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          if (data.row?.surveyLocUuid) {
            return (
              <>
                <span>是</span>
              </>
            )
          } else {
            return (
              <>
                <span>否</span>
              </>
            )
          }
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          if (data.row?.surveyLocUuid) {
            return (
              <>
                <span>是</span>
              </>
            )
          } else {
            return (
              <>
                <span>否</span>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'TransferOffice')}>
                {t('禁用')}
              </span>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const currentRow = ref<PatrolInspectionType>({})
const actionType = ref('')
//表格操作
const action = (row: PatrolInspectionType, type: string) => {
  actionType.value = type
  if (type == 'Detail') {
    dialogVisible.value = true //打开弹窗
    currentRow.value = row
  } else {
    ElMessage.success('禁用')
  }
}

//巡检任务表格导出excel
const ExportTableData = () => {
  const workbook = XLSX.utils.book_new()
  //在table上建立的id属性
  const ws1 = XLSX.utils.table_to_sheet(document.getElementById('table'))
  XLSX.utils.book_append_sheet(workbook, ws1, 'Sheet1')
  XLSX.writeFile(workbook, `巡检任务.xlsx`)
}
//批量选择
const handleSelectionChange = (val) => {
  console.log(val)
}
const DetailRef = ref()
</script>

<template>
  <ContentWrap>
    <BaseButton type="primary" size="small" @click="ExportTableData">
      <Icon icon="ep:download" :size="13" />导出</BaseButton
    >
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      id="table"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="uuid"
      :loading="loading"
      :pagination="{
        total: total,
        pageSize: pageSize
      }"
      @selection-change="handleSelectionChange"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisible" title="任务详情">
    <Detail ref="DetailRef" :current-row="currentRow" :detail-schema="allSchemas.detailSchema"
  /></Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
:deep(.el-form) {
  float: right;
}
</style>
